import { Component, OnInit } from '@angular/core';
import { AxiosService } from '../../axios.service';
import { LocalStorageService } from 'src/app/myService/local-storage.service';
import { Router } from '@angular/router';
import { ActivatedRoute } from '@angular/router';
import { async } from 'q';
@Component({
  selector: 'app-emp-kufang',
  templateUrl: './emp-kufang.component.html',
  styleUrls: ['./emp-kufang.component.scss']
})
export class EmpKufangComponent implements OnInit {
//所有工单数据
public tempData = [];

public listOfData = [];//工单文件区数据

fileInfom;//显示工单对应的文件信息
isOkLoadingfileInfom;

public fileList;//选择要上传的文件
public workName;
uploader;
fileName;//文件名
workerName;//工件名
link;
workOrder;//上传对应的工单号
sheet_order;//工件上传

public unionorder: any;//工单号,
public newValue: any;//"新值"
name;//"表中栏位名称"

addRemark1;//编辑设计备注
isOkLoadingRemark;
designRemark;

splitJudge: string = ',';

// 接收要修改的数据
updateData;

first: any;//首个19码
tail: any;//结尾19码
uploadData; // 上传数据

public workData = [];
//意同workData
public dataWork = [];
public selCNCData = [];

isShow = [];
btnStop = [];
btnStart = [];

value;//计时时间值
totalTime;//数据库中的时间
time;//页面的时间
recordRowClick = -1;

//其他备注
addOtherRemark;
isOkLoadingOthRemark;
RemarkValue;//备注框的值
workKey;

showWarning = {};//工件行显示退回图标
showBigWarning = [];//工单行显示退回图标

isSendVisible;//送出工件
isSendOkLoading;

isFileVisible;//删除文件信息
isFileOkLoading;
id;//文件信息id


timeIndex = 0;
hour;
minutes;
seconds;
timeKey: any = [];

unionKey;
smallKey;
timeDic = {};

//1號機台 2號機台 3號機台 4號機台
selectStatus = [
  {'name':'ALL','checked':true,'select':''},
  { 'name': '1號機台', 'checked': true, 'select': '1號機 ' },
  { 'name': '2號機台', 'checked': true, 'select': '2號機 ' },
  // { 'name': '3號機台', 'checked': true, 'select': '3號機 ' },
  { 'name': '4號機台', 'checked': true, 'select': '4號機 ' },
  { 'name': '5號機台', 'checked': true, 'select': '5號機 ' },
  { 'name': '6號機台', 'checked': true, 'select': '6號機 ' },
  { 'name': '7號機台', 'checked': true, 'select': '7號機 ' },
  // { 'name': '8號機台', 'checked': true, 'select': '8號機 ' },
  { 'name': '9號 走芯機', 'checked': true, 'select': '9號 走芯機' }
];
  constructor(
    public axios: AxiosService,
    private storage: LocalStorageService,
    public activatedRoute:ActivatedRoute,
    private router: Router
  ) {
    this.activatedRoute.params.subscribe((data)=>{
      if (data) {
        console.log("----------------------------\n",data)
        // this.nameTitle = data.name;
        // console.log(this.nameTitle)
      }
     })
   }

  ngOnInit(): void {
     //获取全部数据
     this.getAllData();
  }

  //获取全部数据
 getAllData() {
  this.axios.axiosPost('QueryUnionOrder')
    .then((data) => {
      if (data) {
        // debugger
        console.log(data)
        this.tempData = data['order'];
        for(let i = 0;i<this.tempData.length;i++){
          // console.log(data['order'][i].tip)
          // debugger
          if(this.tempData[i].tip > 0){
            this.showBigWarning.push(true);
          }else{
            this.showBigWarning.push(false);
          }
        }
        this.storage.setStorageData('result', this.tempData);
        // this.QueryWorkOrder();
      }
    })
    .catch((err) => {
      console.log(err);
    })
}

 //查询工单对应的工件信息
 QueryWorkOrder(key){
  this.unionKey = key;
  this.workKey = key;
  this.axios.axiosPost('QueryWorkOrder',{'unionorder':this.tempData[key].union_order})
    .then((data) => {
      console.log(data)
      if (data['result'] === 'ok' && data['order'].length > 0 ) {
        // debugger
        const orderData = data['order'];
        //过滤标准件，只显示加工件
        let a = data['order'].filter((item, i) => {return item.type_flag != 0;})
        this.workData[key] = a;
        this.dataWork = a;
        console.log(this.workData)
        const tempArr = [];
        const timeDefault = [];
        for(let i = 0;i< orderData.length;i++){
          if (orderData[i]['remark'] !=='') {
            tempArr.push(true);
          } else {
            tempArr.push(false);
          }

          // 给点击的小行数据初始化时间
          timeDefault.push('');
        }
        this.showWarning[key] = tempArr;
        this.timeDic[this.unionKey] = timeDefault;
        console.log('1111111\n',this.showWarning)
      }
    })
    .catch((err) => {
      console.log(err);
    })
}

//CNC机台选择
selStatus(item) {
  item.checked = !item.checked;
  this.selCNC(item);
}

//筛选CNC机台
selCNC(data){
  // debugger
  // console.log(data,this.tempData['union_order'])
  // this.axios.axiosPost('QueryCncData', { 'unionorder': this.tempData['union_order'], 'cnc': data.select})
  //   .then((data) => {
  //     console.log(data)
  //     if (data['result'] === 'ok') {
  //       this.tempData = data['order'];
  //     }
  //   })

  // 选中
  if (data.checked) {
    const addCNC = this.dataWork.filter(res => res['cnc_name'] === data.select);
    console.log(addCNC)
    this.selCNCData = this.selCNCData.concat(addCNC);
    console.log(this.selCNCData)
  }
  // 未选中
  if (!data.checked) {
    const deleteCNC = this.workData.filter(res => res['cnc_name'] === data.select);
    console.log(deleteCNC)
    this.selCNCData = this.workData.filter(item => !deleteCNC.some(ele => ele['cnc_name'] === item['cnc_name']));
    console.log(this.selCNCData)
  }
  // this.workData = [];
  this.workData = this.selCNCData;
}

//点击设计备注
addRemark(item) {
  this.addRemark1 = true;
  this.designRemark = item.code_remark;
  this.updateData = item;
}
//确认添加设计备注
addRemarkOk() {
  this.isOkLoadingRemark = true;
  this.addRemark1 = false;
  this.isOkLoadingRemark = false;

  console.log(this.first);
  this.axios.axiosPost('UpdateUnionOrder', { 'unionorder': this.updateData.union_order, 'name': 'code_remark', 'newValue': this.designRemark })
    .then((data) => {
      console.log(data)
      if (data['result'] === 'ok') {
        this.getAllData();
      }
    })
}

//取消添加设计备注
CancelAddRemark() {
  this.addRemark1 = false;
}

currentPageDataChange(qqq) {

}

//点击图标显示此工单的文件信息
downLoad(infom) {
  console.log(infom)
  this.fileInfom = true;
  // this.updateData = infom;
  // debugger
  this.workOrder = infom.union_order;
  this.workerName = infom.name;
  this.workName = this.workOrder;
  this.sheet_order = infom.sheet_order;
  console.log(infom.name,this.workOrder)
  if(infom.name !== undefined){
    this.axios.axiosPost('QueryWorkFiles', { 'unionorder': this.workOrder, 'workorder': infom.name })
    .then((data) => {
      console.log(data)
      if (data['result'] === 'ok') {
        this.listOfData = data['files'];
      }
    })
  }else if(infom.name === undefined){
    this.axios.axiosPost('QueryWorkFiles', { 'unionorder': this.workOrder, 'workorder': this.sheet_order })
    .then((data) => {
      console.log(data)
      if (data['result'] === 'ok') {
        this.listOfData = data['files'];
      }
    })
  }
}

CancelShow(){
  this.fileInfom = false;
}

ShowOK(){
  this.isOkLoadingfileInfom = true;
  this.fileInfom = false;
  this.isOkLoadingfileInfom = false;
}

//上传文件
Upload() {
  // debugger
  if(this.uploadData==null)
  return;
  console.log(this.workOrder,this.workerName)
  if(this.workerName !== undefined){
    this.axios.axiosPost('Upload', { 'unionorder': this.workOrder, 'workorder': this.workerName,
    'filename':this.fileName.files[0]['name'],'filedata':this.uploadData})
    .then((data) => {

      console.log(data)
      if (data['result'] === 'ok') {
        alert("上传成功！")
        this.uploadData = null;
        this.axios.axiosPost('QueryWorkFiles', { 'unionorder': this.workOrder, 'workorder': this.workerName})
        .then((data) => {
          if (data['result'] === 'ok') {
            this.listOfData = data['files'];
          }
        })

      }else{
        alert("上传失败！")
      }
    }).catch(function(err){
      console.log(err)
    })
  }else if(this.workerName === undefined){
    this.axios.axiosPost('Upload', { 'unionorder': this.workOrder, 'workorder': this.sheet_order,
    'filename':this.fileName.files[0]['name'],'filedata':this.uploadData})
    .then((data) => {

      console.log(data)
      if (data['result'] === 'ok') {
        alert("上传成功！")
        this.uploadData = null;
        this.axios.axiosPost('QueryWorkFiles', { 'unionorder': this.workOrder, 'workorder': this.sheet_order})
        .then((data) => {
          if (data['result'] === 'ok') {
            this.listOfData = data['files'];
          }
        })

      }else{
        alert("上传失败！")
      }
    }).catch(function(err){
      console.log(err)
    })
  }
}

//选择要上传的文件名
openFile(event:any): void{
  // debugger
  this.fileName = event.target; //获取点击得到的对象
  const reader = new FileReader();
  reader.onload = (() => {
    if(reader.result){
      this.uploadData = reader.result;
      console.log(reader.result);
    }
  });
  reader.readAsDataURL(this.fileName.files[0]);//将文件转为Base64格式
  console.log("hahahaahahahah\n",reader.result)
}

handleFileCancel(){
  this.isFileVisible = false;
}

downLoadFile(data){
  console.log(data)
  // debugger
  this.fileName = data.file_name;
  this.link = this.axios.domainTest1 + this.workName + '/' + this.fileName;
  console.log(this.fileName, this.link)
}

//删除文件信息
showDelFile(data) {
  this.isFileVisible = true;
  console.log(data)
  this.id = data.id;
}

delFileOk() {
  this.isFileOkLoading = true;
  this.isFileVisible = false;
  this.isFileOkLoading = false;
  this.axios.axiosPost('DeleteWorkFile', { 'id': this.id })
    .then((data) => {
      console.log(data)
      if (data['result'] === 'ok') {
        let listData = this.listOfData.filter(res => res['id'] !== this.id)
        this.listOfData = listData;
      }
    })
}




  //点击行显示计时器
clickLine(bigKey,key){

  if ( this.recordRowClick === -1) {
    this.timeIndex=0;
    this.recordRowClick = key;
    for (let i = 0; i < this.workData[bigKey].length; i++) {
      if (i !== key) {
        this.isShow[i] = false;
      } else {
        this.isShow[i] = true;
      }
    }
    this.btnStart[key] = true;
    console.log('---------------------- \n', this.isShow);
  }
}

//开始计时
 start(item,key,bigKey){
  this.timeKey = key;
  this.smallKey = key;
  console.log(item,key)
  this.btnStop[key] = true;
  this.btnStart[key] = false;
//  debugger
    this.value= setInterval( () => {
          this.setTime(this.timeIndex, this.timeDic);
      },1000);
}

//暂停计时
stop(item,key,bigKey){
  console.log('暂停 ----\n', this.timeDic);
  this.btnStart[key] = true;
  this.btnStop[key] = false;
  clearInterval( this.value);
}

//结束计时
end(item,key,bigKey){
  console.log('结束 ----\n', this.timeDic);
  this.btnStart[key] = false;
  this.btnStop[key] = true;
// debugger
  if(item.speed_time === ''){
    item.speed_time = 0;
    this.totalTime = item.speed_time;
  }else{
    this.totalTime = item.speed_time;
  }
  console.log(this.totalTime)
  // debugger
  const temp: any = this.timeDic[bigKey][key];
  var hour = temp.split(':')[0];
  var min = temp.split(':')[1];
  var sec = temp.split(':')[2];
  var s;
  s = Number(hour*3600) + Number(min*60) + Number(sec);
  // var total;
  // total =  parseInt(this.totalTime) + s;
  // console.log(total,parseInt(this.totalTime))
  this.recordRowClick = -1;
  clearInterval( this.value);
  this.axios.axiosPost('UpdateWorkOrder',{'unionorder':item.union_order,'workorder':item.sheet_order,
                                          'speed_time':s})
    .then((data) => {
      console.log(data)
      if (data['result'] === 'ok') {
        this.timeDic[bigKey].splice(key,1,'00:00:00')
      }
    })
    .catch((err) => {
      console.log(err);
    })
  console.log('11111111111\n', this.isShow)
}

//退回工件
return(item){
  this.unionorder = item.union_order;
  this.workerName = item.sheet_order;
  console.log(item,this.workerName)
  this.addOtherRemark = true;
  let index = item.remark.indexOf(this.storage.getStorageData('user').name)
  if( index === 0 && item['remark']) {
    this.RemarkValue = item.remark + '\n\n';
  }else{
    this.RemarkValue = this.storage.getStorageData('user').name + ' : \n\n' + item.remark;
  }
  console.log(this.RemarkValue)

}

//取消备注
CancelRemark(){
  this.addOtherRemark = false;
}

//添加其他备注（退回）
RemarkOk(){
  // debugger
  this.isOkLoadingOthRemark = true;
  this.addOtherRemark = false;
  this.isOkLoadingOthRemark = false;
  let content = '';
  content = this.RemarkValue;//姓名+内容
  console.log(content)
  this.axios.axiosPost('UpdateWorkOrder',{'unionorder':this.unionorder,'workorder':this.workerName,
                                          'remark':content,'status':2})
    .then((data) => {
      console.log(data)
      if (data['result'] === 'ok') {
         this.QueryWorkOrder(this.workKey);
      }
    })
    .catch((err) => {
      console.log(err);
    })

}
//点击工单号显示CNC
showCNC(item) {
  debugger
  console.log(item)
  const data = {};
  data['union_order'] = item.union_order;
  this.router.navigate(['/CNC', data])
}

//送出按钮
send(item){
  this.isSendVisible = true;
  this.unionorder = item.union_order;
  this.workerName = item.sheet_order;
}

//取消送出
handleSendCancel(){
  this.isSendVisible = false;
}

//确认送出
sendOk(){
  this.isSendOkLoading = true;
  this.isSendVisible = false;
  this.isSendOkLoading = false;
  debugger
  this.axios.axiosPost('UpdateWorkOrder',{'unionorder':this.unionorder,'workorder':this.workerName,
                                           'status':1})
    .then((data) => {
      console.log(data)
      if (data['result'] === 'ok') {

      }
    })
    .catch((err) => {
      console.log(err);
    })
}

//计时器
setTime(timeIndex, timeDic){
// debugger
console.log(1111111)
this.hour = Math.floor(this.timeIndex / 3600);
this.minutes = Math.floor((this.timeIndex - this.hour * 3600) / 60);
this.seconds =  this.timeIndex - this.hour * 3600 - this.minutes * 60;
this.hour = this.hour < 10 ? "0" + this.hour : this.hour;
this.minutes = this.minutes < 10 ? "0" + this.minutes : this.minutes;
this.seconds = this.seconds < 10 ? "0" + this.seconds : this.seconds;
this.timeIndex =  this.timeIndex + 1;
console.log(222222)
const temptime = (this.hour + ":" + this.minutes + ":" + this.seconds).toString();
console.log('temptime ==== \n',temptime);
timeDic[this.unionKey].splice(this.smallKey,1,temptime);
console.log('水水水水水水水水水水水水  \n', timeDic);
}

btn_CNC(data){
console.log(data)
const CNCnum = {};
CNCnum['select'] = data.select;
console.log(CNCnum['select'])
this.router.navigate(['/CNC',CNCnum]);
}

}
